<template>
  <el-dialog v-el-drag-dialog title="资源素材库" width="1200px" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose" destroy-on-close>
    <div style="height: calc(85vh - 135px)">
      <split-pane :min-percent='10' :default-percent='20' split="vertical">
        <template slot="paneL">
          <el-card class="m-l-5">
            <el-tree
              ref="typeTree"
              node-key="id"
              :data="treeData"
              :props="treeProps"
              class="filter-tree"
              default-expand-all
              highlight-current
              :expand-on-click-node="false"
              check-on-click-node
              @node-click="changeType"
            />
          </el-card>
        </template>

        <template slot="paneR">
          <!-- 搜索区域 -->
          <el-card style="margin:0 0 5px 5px" v-show="showSearch">
            <el-form ref="queryForm" :inline="true" :model="queryData">
              <el-form-item prop="Q_loginName_S_LK">
                <el-input v-model="queryData.Q_name_S_LK" placeholder="资源名" />
              </el-form-item>
              <el-form-item class="fr p-r-10">
                <el-button class="filter-item m-l-10" type="primary" round icon="el-icon-search" @click="handleFilter">
                  搜索
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- table区域 -->
          <el-card class="m-l-5">
            <el-row class="m-b-5" type="flex">
              <span class="m-r-10" style="font-weight: bold">{{ selectedType }}</span>
            </el-row>
            <el-row class="m-b-5" :gutter="10">
              <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
              <div class="top-right-btn m-r-10">
                <el-row>
                  <el-button size="mini" plain type="primary" icon="el-icon-check" @click="handleConfirm()">
                    保存
                  </el-button>
                  <el-button v-if="selectionData.length > 0" size="mini" plain type="info" icon="el-icon-refresh" @click="handleClearSelected()">
                    清空已选
                  </el-button>
                </el-row>
              </div>
            </el-row>
            <el-table
              ref="resource_table"
              v-loading="tableLoading"
              row-key="resourceId"
              :data="tableData"
              element-loading-text="加载中"
              border
              fit
              highlight-current-row
              show-overflow-tooltip
              height="300px"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange"
              @current-change="handleRadioChange"
            >
              <el-table-column v-if="!single" type="selection" width="32" />&nbsp;
              <el-table-column v-if="single" width="32">
                <template slot-scope="scope">
                  <el-radio
                    v-model="selectRadio"
                    :label="scope.row.resourceId"
                  >&nbsp;
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type" width="60">
                <template slot-scope="scope">
                  <img :src="setFileImg(scope.row.extension)" style="width: 30px;">
                </template>
              </el-table-column>
              <el-table-column align="center" label="资源名" prop="name" show-overflow-tooltip />
              <el-table-column align="center" label="大小" prop="size" width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div style="padding: 0 10px;">{{ calculateFileSize(scope.row.size) }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="时长" prop="size" width="100" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div style="padding: 0 10px;">{{ calculateVideoTime(scope.row.duration) }}</div>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData(false)" />
          </el-card>
        </template>
      </split-pane>
    </div>
  </el-dialog>
</template>

<script>
import { resourceTable } from '@/api/training/resource'
import { dictTreeData } from '@/api/system/dict'
import { convertTimeMs } from '@/utils'
import SplitPane from 'vue-splitpane'

export default {
  name: 'TrainingResourceTableDialog',
  components: {
    SplitPane
  },
  props: {
    appendToBody: {
      type: Boolean,
      default: true
    },
    single: {
      type: Boolean,
      default: false
    },
    exclude: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      visible: false,
      //  可以识别的文件类型
      fileImgTypeList: [
        'png',
        'jpg',
        'jpeg',
        'docx',
        'doc',
        'ppt',
        'pptx',
        'xls',
        'xlsx',
        'avi',
        'mp4',
        'css',
        'csv',
        'chm',
        'rar',
        'zip',
        'dmg',
        'mp3',
        'open',
        'pdf',
        'rtf',
        'txt',
        'oa',
        'js',
        'html',
        'img',
        'sql',
        'jar',
        'svg',
        'gif',
        'json',
        'exe'
      ],
      //  文件图片Map映射
      fileImgMap: {
        dir: require('@/assets/images/file/dir.png'),
        chm: require('@/assets/images/file/file_chm.png'),
        css: require('@/assets/images/file/file_css.png'),
        csv: require('@/assets/images/file/file_csv.png'),
        png: require('@/assets/images/file/file_pic.png'),
        jpg: require('@/assets/images/file/file_pic.png'),
        jpeg: require('@/assets/images/file/file_pic.png'),
        docx: require('@/assets/images/file/file_word.png'),
        doc: require('@/assets/images/file/file_word.png'),
        ppt: require('@/assets/images/file/file_ppt.png'),
        pptx: require('@/assets/images/file/file_ppt.png'),
        xls: require('@/assets/images/file/file_excel.png'),
        xlsx: require('@/assets/images/file/file_excel.png'),
        mp4: require('@/assets/images/file/file_video.png'),
        avi: require('@/assets/images/file/file_avi.png'),
        rar: require('@/assets/images/file/file_rar.png'),
        zip: require('@/assets/images/file/file_zip.png'),
        dmg: require('@/assets/images/file/file_dmg.png'),
        mp3: require('@/assets/images/file/file_music.png'),
        open: require('@/assets/images/file/file_open.png'),
        pdf: require('@/assets/images/file/file_pdf.png'),
        rtf: require('@/assets/images/file/file_rtf.png'),
        txt: require('@/assets/images/file/file_txt.png'),
        oa: require('@/assets/images/file/file_oa.png'),
        js: require('@/assets/images/file/file_js.png'),
        html: require('@/assets/images/file/file_html.png'),
        img: require('@/assets/images/file/file_img.png'),
        sql: require('@/assets/images/file/file_sql.png'),
        jar: require('@/assets/images/file/file_jar.png'),
        svg: require('@/assets/images/file/file_svg.png'),
        gif: require('@/assets/images/file/file_gif.png'),
        json: require('@/assets/images/file/file_json.png'),
        exe: require('@/assets/images/file/file_exe.png'),
        unknown: require('@/assets/images/file/file_unknown.png')
      },
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      showSearch: true,
      queryData: {
        Q_type_S_EQ: undefined,
        Q_name_S_LK: undefined,
        Q_status_S_EQ: '0',
        Q_resourceId_L_NIN: undefined
      },
      selectedType: undefined,
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectRadio: undefined,
      selectionData: [],
      skipSelectionChange: false
    }
  },
  methods: {
    init() {
      this.$nextTick(() => {
        this.getTreeData()
        this.getTableData(true)
        this.visible = true
      })
    },
    changeType(data, node) {
      this.queryData.Q_type_S_EQ = node.data.title
      this.selectedType = node.name
      this.handleFilter()
    },
    getTreeData() {
      dictTreeData({
        dictGroup: 'sys_file_type',
        from: 'vue'
      }).then(response => {
        this.treeData = response
      }).catch(e => {})
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData(false)
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData(true)
    },
    getTableData(skipSelectionChane) {
      this.skipSelectionChange = skipSelectionChane
      this.queryData.Q_resourceId_L_NIN = this.exclude
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      resourceTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.skipSelectionChange = false
        this.$refs.resource_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
        this.skipSelectionChange = false
      })
    },
    // 根据文件扩展名设置文件图片
    setFileImg(extendName) {
      if (extendName === null) {
        // 文件夹
        return this.fileImgMap.dir
      } else if (!this.fileImgTypeList.includes(extendName)) {
        // 无法识别文件类型的文件
        return this.fileImgMap.unknown
      } else {
        // 可以识别文件类型的文件
        return this.fileImgMap[extendName]
      }
    },
    // 计算文件大小
    calculateFileSize(size) {
      const B = 1024
      const KB = Math.pow(1024, 2)
      const MB = Math.pow(1024, 3)
      const GB = Math.pow(1024, 4)
      if (!size) {
        return '_'
      } else if (size < KB) {
        return (size / B).toFixed(0) + 'KB'
      } else if (size < MB) {
        return (size / KB).toFixed(1) + 'MB'
      } else if (size < GB) {
        return (size / MB).toFixed(2) + 'GB'
      } else {
        return (size / GB).toFixed(3) + 'TB'
      }
    },
    // 计算视频时长
    calculateVideoTime(duration) {
      return convertTimeMs(duration * 1000)
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleRadioChange(row) {
      if (row && this.single) {
        this.selectionData = []
        this.selectionData.push(row)
      }
    },
    handleSelectionChange(selection) {
      if (selection && !this.skipSelectionChange) {
        this.selectionData = this.selectionData.filter(data => {
          let result = false
          selection.forEach(row => {
            if (data.resourceId === row.resourceId) {
              result = false
            }
          })
          return result
        })
        this.selectionData = this.selectionData.concat(selection)
      }
    },
    handleConfirm() {
      if (this.selectionData.length === 0 && this.selectRadio === undefined) {
        this.$modal.msgWarning('请至少选择一项')
        return
      }
      if (this.single) {
        const selected = this.tableData.filter(row => {
          return row.resourceId === this.selectRadio
        })
        this.$emit('confirmDialog', selected)
      } else {
        this.$emit('confirmDialog', this.selectionData)
      }

      this.onClose()
    },
    handleClearSelected() {
      this.selectRadio = undefined
      this.skipSelectionChange = true
      this.$refs.resource_table.clearSelection()
      this.selectionData = []
      this.skipSelectionChange = false
    },
    onClose() {
      this.$refs.queryForm.resetFields()
      this.selectedType = undefined
      this.handleClearSelected()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-tree {
  overflow-y: auto;
}

.filter-tree {
  height: calc(100vh - 370px);
}
</style>
